﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LCA.Utils;
using LCA.Data;
using Composite.Data;
using LCA.Common.Extensions;
using System.Web.Script.Serialization;

public partial class Admin_LCAImpactFactor_Controls_ImpactFactorEditor : System.Web.UI.UserControl
{
    public Guid? FactorId
    {
        get
        {
            return StringHelper.ParseGuid(Request.Params["factorId"]); 
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    protected void ddlFactors_SelectedIndexChanged(object sender, EventArgs e)
    {
        Guid? id = ddlFactors.SelectedValue.ToGuid();

        string queryStr = id.HasValue ? "?factorId=" + id.Value : "";
        PageHelper.AdminPageRedirect(Page, "ManageImpactFactors.aspx" + queryStr);
    }

    public event EventHandler DataSaved;
    public event EventHandler Cancelled;

    protected virtual void OnDataSaved(EditorArgs e)
    {
        if (DataSaved != null)
        {
            DataSaved(this, e);
        }
    }

    protected virtual void OnCancelled(EventArgs e)
    {
        if (Cancelled != null)
        {
            Cancelled(this, e);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        OnCancelled(new EventArgs());
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SaveData();
            EditorArgs args = new EditorArgs();
            args.ItemId = this.FactorId.Value;

            OnDataSaved(args);
        }
    }

    public void SaveData()
    {
        var table = new JavaScriptSerializer().Deserialize<dynamic>(txtImpactFactors.Text);

        using (DataConnection connection = new DataConnection())
        {
            var deletedList = from i in connection.Get<LCA.Data.FlowFactor>()
                                    where i.Factor == this.FactorId.Value
                                    select i;

            foreach (LCA.Data.FlowFactor item in deletedList)
            {
                connection.Delete(item);
            }

            if (table != null)
            {
                LCA.Data.FlowFactor ffa = null;
                foreach(var row in table)
                {
                    string item_id = row["item_id"].ToString();

                    string emission = row["emission"].ToString();
                    string ref_id = row["ref_id"];

                    ffa = connection.CreateNew<LCA.Data.FlowFactor>();
                    ffa.Factor = this.FactorId.Value;
                    ffa.Flow = item_id.ToGuid().Value;
                    ffa.Emission = emission;
                    ffa.Reference = ref_id.ToGuid();

                    connection.Add(ffa);
                }
            }
        }
    }

    public void RefreshComponents()
    {
        using (DataConnection conn = new DataConnection())
        {
            // Load dropdown
            var list = from fac in conn.Get<LCA.Data.Factor>()
                       orderby fac.Name
                       select fac;

            ddlFactors.DataSource = list;
            ddlFactors.DataBind();
            ddlFactors.Items.Insert(0, new ListItem("-- Please Select --", "NULL"));

            plhGrid.Visible = false;
            plhPleaseSelect.Visible = false;
            
            if (FactorId.HasValue)
            {
                plhGrid.Visible = true;

                

                ddlFactors.SelectedValue = FactorId.Value.ToString();
                lnkAddIF.Text = string.Format("+ Add Impact Factors to {0}", ddlFactors.SelectedItem.Text);
                lnkAddIFBottom.Text = string.Format("+ Add Impact Factors to {0}", ddlFactors.SelectedItem.Text);
                
                string headerText = string.Format("Add / Edit Impact Factors to {0}", ddlFactors.SelectedItem.Text);
                ctlImpactFactorModal.RefreshComponents(headerText);

                var factorList = from ffa in conn.Get<LCA.Data.FlowFactor>()
                                 join f in conn.Get<LCA.Data.Flow>() on ffa.Flow equals f.Id
                                 join s in conn.Get<LCA.Data.Reference>() on ffa.Reference equals s.Id into joined
                                 from j in joined.DefaultIfEmpty()
                                 where ffa.Factor == FactorId.Value && f.IsDeleted == false
                                 orderby f.Name
                                 select new
                                 {
                                     item_id = ffa.Flow,
                                     item_name = f.Name,
                                     emission = ffa.Emission,
                                     ref_id  = ffa.Reference,
                                     ref_name = j.Name
                                 };

                txtImpactFactors.Text = new JavaScriptSerializer().Serialize(factorList.ToList());
            }
            else
            {
                plhPleaseSelect.Visible = true;
            }

        }
        

    }
}